﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using TiaoTiaoCode.AutoUpdate.Common.Exceptions;
using TiaoTiaoCode.AutoUpdate.Common.Strings;
using TiaoTiaoCode.AutoUpdate.WebApi.Filters;

namespace TiaoTiaoCode.AutoUpdate.WebApi.Controllers
{
    /// <summary>
    /// Api接口Controller基类
    /// </summary>    
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [ApiExceptionFilter]
    [ApiController]
    [Route("api/[controller]")]
    public abstract class ApiController : ControllerBase
    {
        /// <summary>
        /// 返回成功
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public IActionResult Success()
        {
            return Ok(new { isSucces = true, code = "200", Message = string.Empty });
        }

        /// <summary>
        /// 返回成功
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        [NonAction]
        public IActionResult Success<T>(T obj)
        {
            return Ok(new { isSucces = true, code = "200", Message = string.Empty, data = obj });
        }

        /// <summary>
        /// 用户Id
        /// </summary>
        public string UserId
        {
            get
            {
                var user = HttpContext.User;

                if (user == null || user.Identity == null || !user.Identity.IsAuthenticated) throw new CustomException("401", "无授权用户信息");

                if (!(user.Identity is ClaimsIdentity claims)) throw new CustomException("401", "无授权信息");

                var claim = claims.FindFirst(ClaimTypeString.UserId);

                if (claim == null) throw new CustomException("401", "无效的登录用户信息");

                return claim.Value;
            }
        }
    }
}
